using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Services;


namespace MainGame.GamePlay
{
  public class BoardRenderer : Microsoft.Xna.Framework.DrawableGameComponent
  {
    public BoardRenderer(Game game)
      : base(game)
    {
      UpdateOrder = (int)ComponentOrders.RENDERER;
      DrawOrder = (int)ComponentOrders.RENDERER;
    }

    IBoard board_service;
    public override void Initialize()
    {
      board_service = Game.Services.GetService(typeof(IBoard)) as IBoard;

      base.Initialize();
    }

    SpriteBatch sprite_batch;
    protected override void LoadContent()
    {
      sprite_batch = new SpriteBatch(GraphicsDevice);
      base.LoadContent();
    }

    public override void Draw(GameTime gameTime)
    {
      sprite_batch.Begin();

#warning Cattiva performance: non si usa il content in Draw o Update, ma solo in LoadContent
      var content = Game.Content;
      var tile_width = GraphicsDevice.Viewport.Width / board_service.Width;
      var tile_height = GraphicsDevice.Viewport.Height / board_service.Height;
      for (int i = 0; i < board_service.Width; i++)
      {
        for (int j = 0; j < board_service.Height; j++)
        {
          var color = Color.White;
          switch (board_service.GetTile(i, j))
          {
            case TileState.Hidden:
              color = Color.Gray;
              break;
            case TileState.Board:
              color = Color.Green;
              break;
            case TileState.Marked:
              color = Color.Red;
              break;
            case TileState.Mine:
              color = Color.Black;
              break;
          }
          var x = i * tile_width;
          var z = j * tile_height;
          sprite_batch.Draw(content.Load<Texture2D>("white_pixel"),
            new Rectangle(x + 1, z + 1, tile_width - 2, tile_height - 2),
            color);
          var num_mines = board_service.NumNearestMines(i, j);
          if (num_mines > 0 && board_service.GetTile(i, j) == TileState.Board)
            sprite_batch.DrawString(content.Load<SpriteFont>("small_font"),
              num_mines.ToString(),
              new Vector2(x + 1, z + 1),
              Color.White);
        }
      }

      sprite_batch.End();

      base.Draw(gameTime);
    }
  }
}
